package com.egoo.ticket.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.config.redis.RedisKeyConstant;
import com.egoo.ticket.server.dao.*;
import com.egoo.ticket.server.pojo.dto.SystemMsgDto;
import com.egoo.ticket.server.pojo.dto.WorkOrderTriggerInfoDto;
import com.egoo.ticket.server.pojo.dto.WorkOrderTriggerRelationDto;
import com.egoo.ticket.server.pojo.entity.*;
import com.egoo.ticket.server.pojo.vo.WorkOrderTriggerInfoVo;
import com.egoo.ticket.server.service.*;
import com.egoo.ticket.server.utils.activiti.ActTaskServiceUtil;
import com.egoo.ticket.server.utils.common.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service()
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class TriggerExecuteServiceImpl implements TriggerExecuteService {

	@Autowired
	private WorkOrderTriggerInfoDao workOrderTriggerInfoDao;
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private WorkOrderStatusDao workOrderStatusDao;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private WorkOrderFilterMenuService workOrderFilterMenuService;
	@Autowired
	private EwsUserDao ewsUserDao;
	@Autowired
	private WorkOrderLogService workOrderLogService;
	@Autowired
	private TaskFormDao taskFormDao;
	@Autowired
	private UserService userService;
	@Autowired
	private EripDataSynService eripDataSynService;
	@Autowired
	private CommonUtil commonUtil;
	@Autowired
	private DynamicSqlJoinUtil dynamicSqlJoinUtil;
	@Autowired
	private CreateCodeUtil createCodeUtil;
	@Autowired
	private WorkOrderTypeNodeDao workOrderTypeNodeDao;
	@Autowired
	private WorkOrderTriggerRelationDao workOrderTriggerRelationDao;
	@Autowired
	private WorkOrderRelationMapper workOrderRelationMapper;

	@Value("${server.H5-workorder-detail-url}")
	private String h5WorkorderDetailUrl;

	@Resource(name = "normalRestTemplate")
	private RestTemplate normalRestTemplate;
	@Autowired
	private RestTemplate restTemplate;
	@Value("${server.client-phone-sign}")
	private String clientPhone;
	@Autowired
	private MsgUtil msgUtil;
	@Autowired
	private MsgTemplateMapper msgTemplateMapper;
	/**
	 * TODO 获取可见启用状态工单触发器列表
	 * @author: victor_tang
	 * @createtime: 2020/3/4 22:04
	 * @param workOrderId 1
	 * @return: java.utils.List<com.egoo.ews.service.vo.WorkOrderTriggerInfoVo>
	 */
	private List<WorkOrderTriggerInfoVo> getNomalTriggerInfoList(String workOrderId){
		WorkOrder workOrder = workOrderDao.selectById(workOrderId);
		if (workOrder==null) {
			log.error(workOrderId+"工单可能已被删除,无法获取其工单信息！");
			return null;
		}
		if (StringUtils.isEmpty(workOrder.getTenantId())) {
			log.error(workOrderId+"工单所属租户为空，无法筛选其对应触发器信息！");
			return null;
		}
		WorkOrderTriggerInfoDto workOrderTriggerInfoDto = new WorkOrderTriggerInfoDto();
		workOrderTriggerInfoDto.setStatus(ConstantCode.STATUS_NOMAL);
		workOrderTriggerInfoDto.setTenantId(workOrder.getTenantId());
		workOrderTriggerInfoDto.setWorkOrderTypeId(workOrder.getWorkOrderTypeId().toString());
		return workOrderTriggerInfoDao.selectByCondition(workOrderTriggerInfoDto);
	}
	/**
	 * TODO 根据工单id，遍历触发器列表，满足条件进行执行
	 * @author: victor_tang
	 * @createtime: 2020/1/3 17:23
	 * @param workOrderId 1
	 * @return: void
	 */
	@Override
	public void triggerExecuteByWorkOrderId(String workOrderId) {
		log.info("获取到的触发器key:"+workOrderId);
		List<WorkOrderTriggerInfoVo> nomalTriggerList = getNomalTriggerInfoList(workOrderId);
		log.info("租户可见启用状态的所有触发器列表数据(工单id)==》" + nomalTriggerList);
		if (CollectionUtils.isEmpty(nomalTriggerList)) {
			return;
		}
		// 遍历启用状态的触发器列表
		for (WorkOrderTriggerInfoVo workOrderTriggerInfoVo : nomalTriggerList) {
			// 校验此触发器工单是否可执行
			Boolean flag = checkIsExecuted(workOrderTriggerInfoVo, workOrderId);
			if (flag) {
				triggerExecute(workOrderTriggerInfoVo, workOrderId);
			}
		}
	}
	/**
	 * TODO 校验工单在此触发器下是否执行过
	 * @author: victor_tang
	 * @createtime: 2020/5/12 14:48
	 * @param workOrderTriggerInfoVo 1
	 * @param workOrderId 2
	 * @return: java.lang.Boolean
	 */
	private Boolean checkIsExecuted(WorkOrderTriggerInfoVo workOrderTriggerInfoVo, String workOrderId) {
		if (ConstantCode.TriggerType.MORE.equals(workOrderTriggerInfoVo.getTriggerType())) {
			// 触发器类型设置为多次时，直接返回true
			return true;
		}
		WorkOrderTriggerRelationDto dto = new WorkOrderTriggerRelationDto();
		dto.setTriggerId(workOrderTriggerInfoVo.getId());
		dto.setWorkOrderId(workOrderId);
		List<WorkOrderTriggerRelation> list = workOrderTriggerRelationDao.selectByCondition(dto);
		if (CollectionUtils.isEmpty(list)) {
			return true;
		}
		return false;
	}
	/**
	 * TODO 触发器执行
	 * @author: victor_tang
	 * @createtime: 2020/1/15 11:04
	 * @param workOrderTriggerInfoVo 1
	 * @param workOrderId 2
	 * @return: void
	 */
	private void triggerExecute(WorkOrderTriggerInfoVo workOrderTriggerInfoVo
			,String workOrderId){
		JSONObject triggerCondition = workOrderTriggerInfoVo.getTriggerCondition();
		if (triggerCondition==null) {
			return;
		}
		String sql = dynamicJoinSql(triggerCondition,workOrderId);
		log.info("触发器执行条件查询sql{}"+sql);
		// 判断该工单是否满足触发条件
		List<WorkOrder> workOrderList = workOrderDao.selectBySql(sql);
		if (workOrderList==null||workOrderList.size()==0) {
			// 不满足条件，不触发执行动作
			return;
		}

		JSONObject triggerAction = workOrderTriggerInfoVo.getTriggerAction();
		log.info("触发器执行动作为："+triggerAction);
		JSONArray triggerActionArray = triggerAction.getJSONArray("performTableData");
		if (triggerAction==null||triggerActionArray==null||triggerActionArray.size()==0) {
			log.info(workOrderTriggerInfoVo.getId()+"触发器执行动作为空！");
			return;
		}

		for (int i = 0; i < triggerActionArray.size(); i++) {
			// 执行触发器动作
			dynamicExecuteTrigger(workOrderList.get(0), triggerActionArray.getJSONObject(i));
		}
			// 添加该工单和触发器的执行关系记录
		addWorkOrderAndTriggerExecuteRelation(workOrderTriggerInfoVo,workOrderId);
	}
	/**
	 * TODO 添加工单和触发器执行关系记录
	 * @author: victor_tang
	 * @createtime: 2020/5/12 14:53
	 * @param workOrderTriggerInfoVo 1
	 * @param workOrderId 2
	 * @return: void
	 */
	private void addWorkOrderAndTriggerExecuteRelation(WorkOrderTriggerInfoVo workOrderTriggerInfoVo, String workOrderId) {
		WorkOrderTriggerRelation workOrderTriggerRelation = new WorkOrderTriggerRelation();
		workOrderTriggerRelation.setId(createCodeUtil.getUuid());
		workOrderTriggerRelation.setTriggerId(workOrderTriggerInfoVo.getId());
		workOrderTriggerRelation.setWorkOrderId(workOrderId);
		workOrderTriggerRelation.setCreateTime(new Date());
		workOrderTriggerRelationDao.insert(workOrderTriggerRelation);
	}
	/**
	 * TODO 执行触发器动作
	 * @author: victor_tang
	 * @createtime: 2020/1/15 15:20
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void dynamicExecuteTrigger(WorkOrder workOrder, JSONObject triggerAction){

		String triggerActionCode = triggerAction.getString("dictCode");
		log.info("触发器dictCode为："+triggerActionCode);
		if (ConstantCode.SysDictCode.SET_STATUS.equals(triggerActionCode)) {
			// 设置工单状态
			setWorkOrderStatus(workOrder,triggerAction);
		}
		else if(ConstantCode.SysDictCode.SET_PRIORITY.equals(triggerActionCode)){
			// 设置工单优先级
			setWorkOrderPriority(workOrder,triggerAction);
		}
		else if(ConstantCode.SysDictCode.SET_HANDLER.equals(triggerActionCode)){
			// 设置工单处理人
			setWorkOrderHandlePerson(workOrder,triggerAction);
		}
		else if(ConstantCode.SysDictCode.PUSH_MSG_CREATER.equals(triggerActionCode)){
			// 给创建人发送系统消息
			sendMsgToWorkOrderCreator(workOrder,triggerAction);
		}
		else if(ConstantCode.SysDictCode.PUSH_MSG_HANDLER.equals(triggerActionCode)){
			// 给处理人发送系统消息
			sendMsgToWorkOrderHandler(workOrder,triggerAction);
		}
		else if(ConstantCode.SysDictCode.PUSH_MSG_SYSUSER.equals(triggerActionCode)){
			// 给系统选择用户发送消息
			sendMsgToSysChooseUser(workOrder,triggerAction);
		}
		else if(ConstantCode.SysDictCode.PUSH_MSG_MONITOR.equals(triggerActionCode)){
			// 给工单关注人发送消息
			sendMsgToWorkOrderMonitor(workOrder,triggerAction);
		}
		else if(ConstantCode.SysDictCode.PUSH_INTERFACE.equals(triggerActionCode)){
			// 外部接口推送
			externalInterfacePush(workOrder,triggerAction);
		}
		else if (ConstantCode.SysDictCode.SEND_MSG_EMPLOYEE.equals(triggerActionCode)){
			// 给员工（座席）发送短信
			sendMsg(workOrder,triggerAction);
		}
		else if (ConstantCode.SysDictCode.SEND_MSG_CUSTOMER.equals(triggerActionCode)){
			// 给用户发送短信
			sendMsg(workOrder,triggerAction);
		}
		else if (ConstantCode.SysDictCode.SEND_MSG_CREATOR.equals(triggerActionCode)){
			// 给工单创建人发送短信
			sendMsgToCreator(workOrder,triggerAction);
		}
		else if (ConstantCode.SysDictCode.SEND_MSG_CURRENT_HANDLER.equals(triggerActionCode)){
			// 给工单当前处理人发送短信
			sendMsgToCurrentHandler(workOrder,triggerAction);
		}else if (ConstantCode.SysDictCode.SEND_MSG_SENDER.equals(triggerActionCode)){
			// 给抄送人发短信
			sendMsgToSender(workOrder,triggerAction);
		}else if (ConstantCode.SysDictCode.PUSH_MSG_SENDER.equals(triggerActionCode)){
			//给抄送人发系统消息
			pushMsgToSender(workOrder,triggerAction);
		}else if (ConstantCode.SysDictCode.SEND_EMAIL_HANDLER.equals(triggerActionCode)){
			//给处理人发送邮件
			sendEmailToHandler(workOrder,triggerAction);
		}
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 给处理人发邮件
	 * @Param:
	 * @return:
	 * @Date: 2020/12/7
	 */
	private void sendEmailToHandler(WorkOrder workOrder, JSONObject triggerAction) {
		log.info("进入给当前处理人发送邮件的接口："+workOrder);
//		String content = getFinalMsgTemplateContent(workOrder, triggerAction);
//		if (StringUtils.isEmpty(content)) {
//			log.info("邮件模板内容为空，触发器无法发送！");
//			return;
//		}
		String currentHandlerId = workOrder.getCurrentHandlerId();
		log.info(workOrder.getId()+"工单当前处理人id为："+currentHandlerId);
		log.info(workOrder.getId()+"工单当租户id为："+workOrder.getTenantId());
		if (StringUtils.isEmpty(currentHandlerId)) {
			log.info("工单"+workOrder.getId()+"当前处理人信息id为空，触发器无法给当前工单处理人发送邮件！");
		}
		List<String> userIds = Arrays.asList(currentHandlerId.split(","));
		Map<String, Object> searchMap = new HashMap<>(4);
		searchMap.put("userIds",userIds);
		searchMap.put("tenantId",workOrder.getTenantId());
		List<EwsUser> ewsUsers = ewsUserDao.selectAllUserList(searchMap);
		log.info("工单当前处理人信息为：{}"+ewsUsers);
		String msgContent = triggerAction.getString("msgTemplate");
		String title = triggerAction.getString("msgTemplateTitle");
		String msgTemplateId = triggerAction.getString("msgTemplateId");
		MsgTemplate msgTemplate = msgTemplateMapper.selectById(Integer.valueOf(msgTemplateId));
		msgUtil.sendEmail(ewsUsers,msgTemplate,workOrder);


	}

	/**
	 * @Author: Donny_dong
	 * @Description: 给抄送人发系统消息
	 * @Param:
	 * @return:
	 * @Date: 2020/4/29
	 */
	private void pushMsgToSender(WorkOrder workOrder, JSONObject triggerAction) {
		List<String> list = getSender(workOrder);
		if (CollectionUtils.isEmpty(list)) {
			log.error(workOrder.getId()+"工单抄送人信息为空！");
			return;
		}
		String sysTitle = triggerAction.getString("msgTemplateTitle");
		String sysContent = triggerAction.getString("msgTemplate");
		sysContent = msgUtil.contentHandle(sysContent,workOrder);
		SystemMsgDto<List> systemMsgDto = new SystemMsgDto<List>();
		systemMsgDto.setTargets(list);
		systemMsgDto.setContent(sysContent);
		systemMsgDto.setSenderId("sys");
		systemMsgDto.setTitle(sysTitle);
		JSONObject jsonObject = getPushMsgParamRemark(workOrder.getId(),
				ConstantCode.SystemMsgConfig.IS_JUMP_Y,
				ConstantCode.SystemMsgConfig.WORK_ORDER);
		systemMsgDto.setRemark(jsonObject);
		systemMsgDto.setTenantId(workOrder.getTenantId());
		eripDataSynService.sendSystemMsg(systemMsgDto);
	}


	/**
	 * @Author: Donny_dong
	 * @Description: 获取抄送人
	 * @Param:
	 * @return:
	 * @Date: 2020/4/30
	 */
	private List<String> getSender(WorkOrder workOrder) {
		WorkOrderRelation dto = new WorkOrderRelation();
		dto.setWorkOrderId(workOrder.getId());
		WorkOrderRelation workOrderRelation  = workOrderRelationMapper.selectWorkOrderRelation(dto);
		if (workOrderRelation==null) {
			log.info(workOrder.getId()+"工单未找到关联详情表信息！");
			return 	null;
		}
		String sender = workOrderRelation.getSender();
		if (StringUtils.isEmpty(sender)) {
			return null;
		}
		List<String> strings = Arrays.asList(sender.split(","));
		return strings;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 给抄送人发短信
	 * @Param:
	 * @return:
	 * @Date: 2020/4/29
	 */
	private void sendMsgToSender(WorkOrder workOrder, JSONObject triggerAction) {
		String content = getFinalMsgTemplateContent(workOrder, triggerAction);
		if (StringUtils.isEmpty(content)){
			log.info("短信模板:"+content);
			return;
		}
		JSONObject jsonObject = new JSONObject();
		HashMap<String, Object> hashMap = new HashMap<>(4);
		List<String> sender = getSender(workOrder);
		if (CollectionUtils.isEmpty(sender)) {
			log.error(workOrder.getId()+"工单抄送人信息为空！");
			return;
		}
		hashMap.put("userIds",sender);
		hashMap.put("tenantId",workOrder.getTenantId());
		List<EwsUser> ewsUserList = ewsUserDao.selectAllUserList(hashMap);
		for (EwsUser ewsUser: ewsUserList) {
			jsonObject.put("phoneNumber",ewsUser.getPhone());
			jsonObject.put("content",content);
			jsonObject.put("workOrderId",workOrder.getId());
			jsonObject.put("msgTypeName",triggerAction.getString("msgTemplateTitle"));
			jsonObject.put("userId",ConstantCode.SYSTEM_OPERATION_LOGO);
//			jsonObject.put("clientPhone",workOrder.getPhone());
			jsonObject.put("tenantId",workOrder.getTenantId());
			log.info("工单当前处理人电话为："+ewsUser.getPhone());
			log.info("给当前处理人发送的短信模板为："+content);
			eripDataSynService.sendMsg(jsonObject);
		}
	}

	/**
	 * TODO 给工单创建人发送短信
	 * @author: victor_tang
	 * @createtime: 2020/4/2 11:55
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void sendMsgToCreator(WorkOrder workOrder, JSONObject triggerAction){
		String content = getFinalMsgTemplateContent(workOrder, triggerAction);
		if (StringUtils.isEmpty(content)) {
			log.info("短信模板内容为空，触发器无法发送短信！");
			return;
		}
		EwsUser ewsUser = ewsUserDao.selectById(workOrder.getCreateUserId());
		if (ewsUser==null) {
			log.info("工单"+workOrder+"创建人信息为空，触发器无法发送短信！");
			return;
		}
		if (StringUtils.isEmpty(ewsUser.getPhone())) {
			log.info("工单"+workOrder+"创建人"+ewsUser.getName()+
					"的手机号码为空，触发器无法发送短信！");
			return;
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("phoneNumber",ewsUser.getPhone());
		jsonObject.put("content",content);
		jsonObject.put("tenantId",workOrder.getTenantId());
		jsonObject.put("userId",ConstantCode.SYSTEM_OPERATION_LOGO);
//		jsonObject.put("clientPhone",workOrder.getPhone());
		jsonObject.put("msgTypeName",triggerAction.getString("msgTemplateTitle"));
		jsonObject.put("workOrderId",workOrder.getId());
		eripDataSynService.sendMsg(jsonObject);
	}
	/**
	 * TODO 给工单当前处理人发送短信
	 * @author: victor_tang
	 * @createtime: 2020/4/2 11:55
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	public void sendMsgToCurrentHandler(WorkOrder workOrder, JSONObject triggerAction){
		log.info("进入给当前处理人发送短信接口："+workOrder);
		String content = getFinalMsgTemplateContent(workOrder, triggerAction);
		if (StringUtils.isEmpty(content)) {
			log.info("短信模板内容为空，触发器无法发送短信！");
			return;
		}
		String currentHandlerId = workOrder.getCurrentHandlerId();
		log.info(workOrder.getId()+"工单当前处理人id为："+currentHandlerId);
		log.info(workOrder.getId()+"工单当租户id为："+workOrder.getTenantId());
		if (StringUtils.isEmpty(currentHandlerId)) {
			log.info("工单"+workOrder.getId()+"当前处理人信息id为空，触发器无法给当前工单处理人发送短信！");
		}
		List<String> userIds = Arrays.asList(currentHandlerId.split(","));
		Map<String, Object> searchMap = new HashMap<>(4);
		searchMap.put("userIds",userIds);
		searchMap.put("tenantId",workOrder.getTenantId());
		List<EwsUser> ewsUsers = ewsUserDao.selectAllUserList(searchMap);
		log.info("工单当前处理人信息为：{}"+ewsUsers);
		if (ewsUsers==null || ewsUsers.size()==0) {
			log.info("工单"+workOrder.getId()+"处理人信息未找到，无法给工单当前处理人发送短信！");
		}
		for (EwsUser ewsUser : ewsUsers) {
			String phone = ewsUser.getPhone();
			if (StringUtils.isEmpty(phone)) {
				log.info("工单"+workOrder.getId()+"处理人"+ewsUser.getName()+
						"未录取手机号，触发器无法发送短信！");
				continue;
			}
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("phoneNumber",phone);
			jsonObject.put("content",content);
			jsonObject.put("tenantId",workOrder.getTenantId());
			jsonObject.put("userId",ConstantCode.SYSTEM_OPERATION_LOGO);
//			jsonObject.put("clientPhone",workOrder.getPhone());
			jsonObject.put("msgTypeName",triggerAction.getString("msgTemplateTitle"));
			jsonObject.put("workOrderId",workOrder.getId());
			eripDataSynService.sendMsg(jsonObject);
		}
	}
	/**
	 * TODO 获取最终发送短信模板
	 * @author: victor_tang
	 * @createtime: 2020/4/2 13:27
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: java.lang.String
	 */
	private String getFinalMsgTemplateContent(WorkOrder workOrder, JSONObject triggerAction){
		String msgContent = triggerAction.getString("msgTemplate");
		log.info("获取触发器短信模板内容为："+msgContent);
		if (StringUtils.isEmpty(msgContent)) {
			log.info("触发器配置短信模板内容为空！");
			return null;
		}
		//替换节点处理时长
//		WorkOrderTypeNodeVo workOrderTypeNodeVo = workOrderTypeNodeDao.selectById(workOrder.getCurrentWorkOrderNodeId());
//		if (workOrderTypeNodeVo !=null && workOrderTypeNodeVo.getContent()!= null) {
//			log.info("进入替换节点处理时长");
//			String dealTime = workOrderTypeNodeVo.getContent().getString("dealtime");
//			if (StringUtils.isNotBlank(dealTime)) {
//				msgContent.replace("{timer}", dealTime);
//			}
//		}
		// 替换工单当前处理人信息
//		EwsUser ewsUser = ewsUserDao.selectById(workOrder.getBusinessHandlerId());
//		if (ewsUser != null) {
//			log.info("进入替换工程师和电话");
//			if (StringUtils.isNotBlank(ewsUser.getName())) {
//				msgContent.replace("{engineerName}",ewsUser.getName());
//			}
//			if (StringUtils.isNotBlank(ewsUser.getPhone())) {
//				msgContent.replace("{phone}",ewsUser.getPhone());
//			}
//		}
		// 替换短信模板配置变量名
		return msgUtil.contentHandle(msgContent,workOrder);
//				msgContent
//				.replace(ConstantCode.TemplateConfig.WORK_ORDER_ID, workOrder.getId())
//				.replace(ConstantCode.TemplateConfig.WORK_ORDER_URL,h5WorkorderDetailUrl);
	}
	/**
	 * @Author: Donny_dong
	 * @Description: send msg
	 * @Param:
	 * @return:
	 * @Date: 2020/3/27
	 */
	private void sendMsg(WorkOrder workOrder, JSONObject triggerAction) {
		JSONObject jsonObject = new JSONObject();
		String msgContent = getFinalMsgTemplateContent(workOrder, triggerAction);
		String dictCode = triggerAction.getString("dictCode");
		if (ConstantCode.SysDictCode.SEND_MSG_CUSTOMER.equals(dictCode)) {
			jsonObject.put("phoneNumber",workOrder.getCustomField().getString(clientPhone));
			jsonObject.put("content",msgContent);
			jsonObject.put("workOrderId",workOrder.getId());
			jsonObject.put("msgTypeName",triggerAction.getString("msgTemplateTitle"));
//			jsonObject.put("clientPhone",workOrder.getPhone());
			jsonObject.put("userId",ConstantCode.SYSTEM_OPERATION_LOGO);
			jsonObject.put("tenantId",workOrder.getTenantId());
//			log.info("客户电话为："+workOrder.getPhone());
			log.info("给客户发送的短信模板为："+msgContent);
			eripDataSynService.sendMsg(jsonObject);
		}
		else if (ConstantCode.SysDictCode.SEND_MSG_EMPLOYEE.equals(dictCode)){
			// 获取执行动作中的员工信息列表
			List<EwsUser> ewsUsersList = getUserListByTriggerAction(triggerAction, workOrder);
			for (EwsUser ewsUser:ewsUsersList) {
				jsonObject.put("phoneNumber",ewsUser.getPhone());
				jsonObject.put("content",msgContent);
				jsonObject.put("workOrderId",workOrder.getId());
				jsonObject.put("msgTypeName",triggerAction.getString("msgTemplateTitle"));
				jsonObject.put("userId",ConstantCode.SYSTEM_OPERATION_LOGO);
//				jsonObject.put("clientPhone",workOrder.getPhone());
				jsonObject.put("tenantId",workOrder.getTenantId());
				log.info("工单当前处理人电话为："+ewsUser.getPhone());
				log.info("给当前处理人发送的短信模板为："+msgContent);
				eripDataSynService.sendMsg(jsonObject);
			}
		}
	}
	/**
	 * TODO 获取执行动作中的用户信息列表
	 * @author: victor_tang
	 * @createtime: 2020/4/15 17:03
	 * @param triggerAction 1
	 * @param workOrder 2
	 * @return: java.utils.List<com.egoo.ews.service.vo.EwsUser>
	 */
	private List<EwsUser> getUserListByTriggerAction(JSONObject triggerAction,
                                                     WorkOrder workOrder){
		String type = triggerAction.getString("containValue");
		List<String> assignee = null;
		if(ConstantCode.UserRoleDeptType.DEPT.equals(type)){
			JSONArray idArrary = triggerAction.getJSONArray("containValueUser");
			assignee = commonUtil.splitDeptCode(idArrary.toJSONString());
		}else {
			assignee = triggerAction.getObject("containValueUser",List.class);
		}
		return userService.getUserListByTypeAndTypeIds(type, assignee, workOrder.getTenantId());
	}

	/**
	 * TODO 给创建人发送系统消息
	 * @author: victor_tang
	 * @createtime: 2020/2/16 12:09
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void sendMsgToWorkOrderCreator(WorkOrder workOrder,
								   JSONObject triggerAction){
		// 获取工单创建人信息
		String createUserId = workOrder.getCreateUserId();
		EwsUser ewsUser = ewsUserDao.selectById(createUserId);
		// 获取发送信息内容
		String sysTitle = triggerAction.getString("msgTemplateTitle");
		String sysContent = triggerAction.getString("msgTemplate");
		sysContent = msgUtil.contentHandle(sysContent,workOrder);
		// 拼接请求参数，调用erip消息中心接口
		SystemMsgDto systemMsgDto = new SystemMsgDto();
		systemMsgDto.setSenderId(ConstantCode.SystemMsgConfig.SENDER_ID_SYS);
		systemMsgDto.setTitle(sysTitle);
		List<String> receiveUserIds = new ArrayList<>();
		receiveUserIds.add(createUserId);
		systemMsgDto.setTargets(receiveUserIds);
		systemMsgDto.setContent(sysContent);
		systemMsgDto.setTenantId(workOrder.getTenantId());
		JSONObject jsonObject = getPushMsgParamRemark(workOrder.getId(),
				ConstantCode.SystemMsgConfig.IS_JUMP_Y,
				ConstantCode.SystemMsgConfig.WORK_ORDER);
		systemMsgDto.setRemark(jsonObject);
		eripDataSynService.sendSystemMsg(systemMsgDto);
	}
	/**
	 * TODO 设置推送消息字段remark值
	 * @author: victor_tang
	 * @createtime: 2020/4/1 16:00
	 * @param orderId 1
	 * @param isJump 2
	 * @param systemType 3
	 * @return: com.alibaba.fastjson.JSONObject
	 */
	private JSONObject getPushMsgParamRemark(String orderId, String isJump,
                                             String systemType){
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(ConstantCode.SystemMsgConfig.REMARK_ORDER_ID,orderId);
		jsonObject.put(ConstantCode.SystemMsgConfig.REMARK_IS_JUMP,isJump);
		jsonObject.put(ConstantCode.SystemMsgConfig.REMARK_SYSTEM_TYPE,systemType);
		return jsonObject;
	}
	/**
	 * TODO 给工单处理人发送消息
	 * @author: victor_tang
	 * @createtime: 2020/2/16 12:09
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	public void sendMsgToWorkOrderHandler(WorkOrder workOrder,
									 JSONObject triggerAction){
		// 获取工单处理人信息列表
		String currentHandlerIdsStr = workOrder.getCurrentHandlerId();
		if (StringUtils.isEmpty(currentHandlerIdsStr)) {
			log.info(workOrder.getId()+"工单处理人信息为空！");
			return;
		}
		List<EwsUser> ewsUserList = getUserListByIdsStr(currentHandlerIdsStr);
		// 获取发送信息内容
		String sysTitle = triggerAction.getString("msgTemplateTitle");
		String sysContent = triggerAction.getString("msgTemplate");
		sysContent = msgUtil.contentHandle(sysContent,workOrder);
		// 拼接请求参数，调用erip消息中心接口
		SystemMsgDto systemMsgDto = new SystemMsgDto();
		systemMsgDto.setSenderId(ConstantCode.SystemMsgConfig.SENDER_ID_SYS);
		systemMsgDto.setTitle(sysTitle);
		List<String> receiveUserIds = Arrays.asList(currentHandlerIdsStr.split(","));
		systemMsgDto.setTargets(receiveUserIds);
		systemMsgDto.setContent(sysContent);
		systemMsgDto.setTenantId(workOrder.getTenantId());
		JSONObject jsonObject = getPushMsgParamRemark(workOrder.getId(),
				ConstantCode.SystemMsgConfig.IS_JUMP_Y,
				ConstantCode.SystemMsgConfig.WORK_ORDER);
		systemMsgDto.setRemark(jsonObject);
		eripDataSynService.sendSystemMsg(systemMsgDto);

	}
	/**
	 * TODO 给执行动作指定的系统用户发送消息
	 * @author: victor_tang
	 * @createtime: 2020/2/16 12:09
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void sendMsgToSysChooseUser(WorkOrder workOrder,
								   JSONObject triggerAction){
		// 获取执行动作指定用户信息
		String type = triggerAction.getString("containValue");
		if (StringUtils.isEmpty(type)) {
			log.info("触发器选择指定用户类型为空！");
			return;
		}
		List<String> ids = triggerAction.getObject("containValueUser", List.class);
		List<EwsUser> userList = userService.getUserListByTypeAndTypeIds(type, ids,workOrder.getTenantId());
		if (userList==null) {
			log.info("触发器选择指定用户信息获取为空！");
			return;
		}
		// 获取发送信息内容
		String sysTitle = triggerAction.getString("msgTemplateTitle");
		String sysContent = triggerAction.getString("msgTemplate");
		sysContent = msgUtil.contentHandle(sysContent,workOrder);
		// 拼接请求参数，调用erip消息中心接口
		SystemMsgDto systemMsgDto = new SystemMsgDto();
		systemMsgDto.setSenderId(ConstantCode.SystemMsgConfig.SENDER_ID_SYS);
		systemMsgDto.setTitle(sysTitle);
		List<String> userIds = new ArrayList<>();
		for (String id : ids) {
			userIds.add(id);
		}
		systemMsgDto.setTargets(userIds);
		systemMsgDto.setContent(sysContent);
		JSONObject jsonObject = getPushMsgParamRemark(workOrder.getId(),
				ConstantCode.SystemMsgConfig.IS_JUMP_Y,
				ConstantCode.SystemMsgConfig.WORK_ORDER);
		systemMsgDto.setRemark(jsonObject);
		systemMsgDto.setTenantId(workOrder.getTenantId());
		eripDataSynService.sendSystemMsg(systemMsgDto);
	}
	/**
	 * TODO 给工单关注人发送消息
	 * @author: victor_tang
	 * @createtime: 2020/2/16 12:09
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void sendMsgToWorkOrderMonitor(WorkOrder workOrder,
								   JSONObject triggerAction){
		// 获取工单关注人信息列表
		WorkOrderRelation workOrderRelation = getByWorkOrderId(workOrder.getId());
		String workOrderMonitorId = workOrderRelation.getWorkOrderMonitorId();
		if (StringUtils.isEmpty(workOrderMonitorId)) {
			log.info(workOrder.getId()+"工单无用户关注！");
			return;
		}
//		List<EwsUser> ewsUserList = getUserListByIdsStr(workOrderMonitorId);
		// 获取发送信息内容
		String sysTitle = triggerAction.getString("msgTemplateTitle");
		String sysContent = triggerAction.getString("msgTemplate");
		sysContent = msgUtil.contentHandle(sysContent,workOrder);
		List<String> workOrderMonitorIds = Arrays.asList(workOrderMonitorId.split(","));
		List<String> ids = workOrderMonitorIds.stream().filter(n -> n.equals(workOrderMonitorIds.get(workOrderMonitorIds.size() - 1))).collect(Collectors.toList());

		// 拼接请求参数，调用erip消息中心接口
		SystemMsgDto<List> systemMsgDto = new SystemMsgDto<>();
		ArrayList<String> objects = new ArrayList<>();
		systemMsgDto.setTitle(sysTitle);
		systemMsgDto.setContent(sysContent);
		systemMsgDto.setSenderId(ConstantCode.SystemMsgConfig.SENDER_ID_SYS);
		systemMsgDto.setTargets(ids);
		systemMsgDto.setTenantId(workOrder.getTenantId());
		JSONObject jsonObject = getPushMsgParamRemark(workOrder.getId(),
				ConstantCode.SystemMsgConfig.IS_JUMP_Y,
				ConstantCode.SystemMsgConfig.WORK_ORDER);
		systemMsgDto.setRemark(jsonObject);
		eripDataSynService.sendSystemMsg(systemMsgDto);

	}

	/**
	 * @Author: Donny_dong
	 * @Description: 根据工单id获取一条WorkOrderRelation
	 * @Param:
	 * @return:
	 * @Date: 2020/4/26
	 */
	private WorkOrderRelation getByWorkOrderId(String workOrderId) {
		WorkOrderRelation workOrderRelation = new WorkOrderRelation();
		workOrderRelation.setWorkOrderId(workOrderId);
		workOrderRelation = workOrderRelationMapper.selectWorkOrderRelation(workOrderRelation);
		return workOrderRelation;
	}

	/**
	 * TODO 根据用户ids字符串获取用户信息列表
	 * @author: victor_tang
	 * @createtime: 2020/2/16 12:38
	 * @param userIdsStr 1
	 * @return: java.utils.List<com.egoo.ews.service.vo.EwsUser>
	 */
	private List<EwsUser> getUserListByIdsStr(String userIdsStr){
		if (StringUtils.isEmpty(userIdsStr)) {
			log.info("getUserListByIdsStr{}用户ids字符串为空！");
			return null;
		}
		List<String> userIds = Arrays.asList(userIdsStr.split(","));
		Map<String, Object> searchMap = new HashMap<>(2);
		searchMap.put("userIds",userIds);
		return ewsUserDao.selectAllUserList(searchMap);
	}
	/**
	 * TODO 触发器外部接口推送处理
	 * @author: victor_tang
	 * @createtime: 2020/2/11 12:28
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void externalInterfacePush(WorkOrder workOrder, JSONObject triggerAction){
		JSONObject interfaceRequestData = triggerAction.getJSONObject(
				"performTableData").getJSONObject("containValue");

		String url = interfaceRequestData.getString("URL");
		JSONArray body = interfaceRequestData.getJSONArray("body");
		String headers = interfaceRequestData.getString("Headers");

		JSONObject pushInterfaceParams = new JSONObject();
		// 组装工单基础字段信息
		pushInterfaceParams = handleWorkOrderBaseField(pushInterfaceParams, body, workOrder);

		// 组装表单字段信息
		pushInterfaceParams = handleWorkOrderTemplateField(pushInterfaceParams, body, workOrder);

		// 请求外部接口
		Map<String, Object> headerMap = (Map) JSON.parse(headers);
		log.info("触发器外部接口推送URL====>"+url);
		log.info("触发器外部接口推送header参数"+headerMap);
		HttpHeaders httpHeaders = new HttpHeaders();
		for (String headerKey:headerMap.keySet()
			 ) {
			httpHeaders.add(headerKey,(String) headerMap.get(headerKey));
		}
		MultiValueMap<String, Object> linkedMultiValueMap = new LinkedMultiValueMap<>();
		Map<String,Object> bodyMap = JSONObject.toJavaObject(pushInterfaceParams, Map.class);
		for (String bodyKey:bodyMap.keySet()
			 ) {
			linkedMultiValueMap.add(bodyKey,bodyMap.get(bodyKey));
		}
		HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(linkedMultiValueMap,httpHeaders);
		try {
			String response = normalRestTemplate.postForObject(url,
					httpEntity,String.class);

			log.info("触发器外部接口推送响应结果为{}"+response);

		} catch (Exception e) {
			log.error("触发器外部接口推送io异常！");
		}

	}
	/**
	 * TODO 组装表单字段信息
	 * @author: victor_tang
	 * @createtime: 2020/2/12 19:42
	 * @param pushInterfaceParams 1
	 * @param body 2
	 * @param workOrder 3
	 * @return: com.alibaba.fastjson.JSONObject
	 */
	private JSONObject handleWorkOrderTemplateField(JSONObject pushInterfaceParams,
                                                    JSONArray body, WorkOrder workOrder){
		if (body==null || body.size()==0) {
			log.error("推送外部接口，执行动作参数配置为空！");
			return null;
		}
		for (int i = 0; i < body.size(); i++) {
			Integer formTemplateId = body.getJSONObject(i).getInteger("formTemplateId");
			Integer workOrderTypeId = body.getJSONObject(i).getInteger("workOrderTypeId");
			Integer workOrderTypeNodeId = body.getJSONObject(i).getInteger("workOrderTypeNodeId");
			if (formTemplateId == null||workOrderTypeId ==null ||workOrderTypeNodeId==null) {
				// 基础字段跳过处理
				continue;
			}

			String innerFieldName = body.getJSONObject(i).getString("innerFieldName");
			String externalFieldName= body.getJSONObject(i).getString("externalFieldName");
			String externalFieldValue= body.getJSONObject(i).getString("externalFieldValue");

			// 获取该工单 工单类型  工单节点  模板的任务content
			Map<String, Object> searchMap = new HashMap<>(8);
			searchMap.put("processInstanceId",workOrder.getProcessInstanceId());
			searchMap.put("workOrderTypeNodeId",workOrderTypeNodeId);
			searchMap.put("workOrderTypeId",workOrderTypeId);
			searchMap.put("formTemplateId",formTemplateId);
			TaskForm taskForm = taskFormDao.selectFiledContentByCondition(searchMap);
			if (taskForm==null||taskForm.getContent()==null) {
				log.error("触发器接口推送表单"+innerFieldName+"字段查询失败!");
				continue;
			}

			JSONObject taskFormContent = taskForm.getContent();
			// 筛选，获取表单字段值
			String templateFieldValue = getTemplateFieldValue(taskFormContent, innerFieldName);

			// 组装请求参数key/value
			if (StringUtils.isNotBlank(templateFieldValue)) {
				pushInterfaceParams.put(externalFieldName,templateFieldValue);
			}else{
				pushInterfaceParams.put(externalFieldName,externalFieldValue);
			}
		}
		return pushInterfaceParams;
	}
	/**
	 * TODO 获取表单字段值
	 * @author: victor_tang
	 * @createtime: 2020/2/12 19:25
	 * @param taskFormContent 1
	 * @param innerFieldName 2
	 * @return: java.lang.String
	 */
	private String getTemplateFieldValue(JSONObject taskFormContent, String innerFieldName){
		if (StringUtils.isEmpty(innerFieldName)||taskFormContent==null) {
			return null;
		}
		// 解析匹配表单字段
		JSONArray taskFormContentJsonArray =
				taskFormContent.getJSONArray(ConstantCode.FormTemplateType.LIST);

		for (int i = 0; i < taskFormContentJsonArray.size(); i++) {
			JSONObject fieldContentJsonObj=
					taskFormContentJsonArray.getJSONObject(i);
			// 获取不是栅格布局类型的字段的值
			String model =
					fieldContentJsonObj.getString(ConstantCode.FormTemplateType.MODEL);
			String type =
					fieldContentJsonObj.getString(ConstantCode.FormTemplateType.TYPE);
			if (innerFieldName.equals(model)) {
				// 非栅格布局字段处理
				JSONObject returnJsonObj =
						getTemplateNoGridFieldValue(fieldContentJsonObj,innerFieldName);
				if (returnJsonObj.getBoolean("isMatch")) {
					return returnJsonObj.getString("fieldValue");
				}

			}else if (ConstantCode.FormTemplateType.GRID.equals(type)){
				// 栅格布局字段处理
				JSONObject returnJsonObj =
						getTemplateGridFieldValue(fieldContentJsonObj, innerFieldName);
				if (returnJsonObj.getBoolean("isMatch")) {
					return returnJsonObj.getString("fieldValue");
				}
			}
		}
		return null;
	}
	/**
	 * TODO 筛选栅格布局字段，获取字段值
	 * @author: victor_tang
	 * @createtime: 2020/2/13 20:32
	 * @param fieldContent 1
	 * @param innerFieldName 2
	 * @return: com.alibaba.fastjson.JSONObject
	 */
	private JSONObject getTemplateGridFieldValue(JSONObject fieldContent, String innerFieldName){
		JSONObject returnJsonObj = new JSONObject();

		JSONArray fiedContentjsonArray = fieldContent.getJSONArray(ConstantCode.FormTemplateType.COLUMNS);
		for (int i = 0; i < fiedContentjsonArray.size(); i++) {
			JSONArray fiedContentListjsonArray =
					fiedContentjsonArray.getJSONObject(i).getJSONArray(ConstantCode.FormTemplateType.LIST);
			for (int j = 0; j < fiedContentListjsonArray.size(); i++) {
				JSONObject fiedContentJsonObj = fiedContentListjsonArray.getJSONObject(i);
				if (!innerFieldName.equals(fiedContentJsonObj.getString(ConstantCode.FormTemplateType.MODEL))) {
					continue;
				}
				String fieldValue=
						fiedContentJsonObj.getJSONObject(ConstantCode.FormTemplateType.OPTIONS)
						.getString(ConstantCode.FormTemplateType.DEFAULT_VALUE);
				returnJsonObj.put("isMatch",true);
				returnJsonObj.put("fieldValue",fieldValue);
				return returnJsonObj;
			}
		}
		returnJsonObj.put("isMatch",false);
		return returnJsonObj;
	}
	/**
	 * TODO 筛选非栅格布局字段，获取字段值
	 * @author: victor_tang
	 * @createtime: 2020/2/13 20:03
	 * @param fieldContent 1
	 * @param innerFieldName 2
	 * @return: java.lang.String
	 */
	private JSONObject getTemplateNoGridFieldValue(JSONObject fieldContent,
                                                   String innerFieldName){
		JSONObject returnJsonObj = new JSONObject();
		String model =
				fieldContent.getString(ConstantCode.FormTemplateType.MODEL);
		if (innerFieldName.equals(model)) {
			returnJsonObj.put("isMatch",true);
			returnJsonObj.put("fieldValue",
					fieldContent.getJSONObject(ConstantCode.FormTemplateType.OPTIONS)
							.getString(ConstantCode.FormTemplateType.DEFAULT_VALUE));

			return returnJsonObj;
		}
		returnJsonObj.put("isMatch",false);
		return returnJsonObj;
	}
	/**
	 * TODO 组装工单基础字段信息
	 * @author: victor_tang
	 * @createtime: 2020/2/12 17:33
	 * @param pushInterfaceParams 1
	 * @param body 2
	 * @param workOrder 3
	 * @return: com.alibaba.fastjson.JSONObject
	 */
	private JSONObject handleWorkOrderBaseField(JSONObject pushInterfaceParams,
                                                JSONArray body, WorkOrder workOrder){

		WorkOrderRelation workOrderRelation = getByWorkOrderId(workOrder.getId());
		if (body==null || body.size()==0) {
			log.error("推送外部接口，执行动作参数配置为空！");
			return null;
		}
		for (int i = 0; i < body.size(); i++) {
			Integer formTemplateId = body.getJSONObject(i).getInteger("formTemplateId");
			Integer workOrderTypeId = body.getJSONObject(i).getInteger("workOrderTypeId");
			Integer workOrderTypeNodeId = body.getJSONObject(i).getInteger("workOrderTypeNodeId");
			if (formTemplateId!=null||workOrderTypeId!=null||workOrderTypeNodeId!=null) {
				// 表单字段跳过处理
				continue;
			}

			String innerFieldName = body.getJSONObject(i).getString("innerFieldName");
			String externalFieldName= body.getJSONObject(i).getString("externalFieldName");
			String externalFieldValue= body.getJSONObject(i).getString("externalFieldValue");
			// 工单标题
//			if (ConstantCode.WorkOrderBaseFieldMeanig.TITLE.equals(innerFieldName)) {
//				if (StringUtils.isNotBlank(workOrder.getTitle())) {
//					pushInterfaceParams.put(externalFieldName, workOrder.getTitle());
//				} else {
//					pushInterfaceParams.put(externalFieldName, externalFieldValue);
//				}
//				continue;
//			}
			// 外部工单id
			if (ConstantCode.WorkOrderBaseFieldMeanig.EXTERNAL_WORK_ORDERID_FIELD.equals(innerFieldName)) {
				if (StringUtils.isNotBlank(workOrderRelation.getExternalWorkOrderId())) {
					pushInterfaceParams.put(externalFieldName, workOrderRelation.getExternalWorkOrderId());
				} else {
					pushInterfaceParams.put(externalFieldName, externalFieldValue);
				}
				continue;
			}
			// 工单来源
//			if (ConstantCode.WorkOrderBaseFieldMeanig.SOURCE_FIELD.equals(innerFieldName)) {
//				if (StringUtils.isNotBlank(workOrder.getSource())) {
//					pushInterfaceParams.put(externalFieldName, workOrder.getSource());
//				} else {
//					pushInterfaceParams.put(externalFieldName, externalFieldValue);
//				}
//				continue;
//			}
			// 工单优先级
//			if (ConstantCode.WorkOrderBaseFieldMeanig.PRIORITY_FIELD.equals(innerFieldName)) {
//				if (StringUtils.isNotBlank(workOrder.getPriority())) {
//					pushInterfaceParams.put(externalFieldName, workOrder.getPriority());
//				} else {
//					pushInterfaceParams.put(externalFieldName, externalFieldValue);
//				}
//				continue;
//			}
			// 客户名称
//			if (ConstantCode.WorkOrderBaseFieldMeanig.CLIENT_NAME_FIELD.equals(innerFieldName)) {
//				if (StringUtils.isNotBlank(workOrder.getClientName())) {
//					pushInterfaceParams.put(externalFieldName, workOrder.getClientName());
//				} else {
//					pushInterfaceParams.put(externalFieldName, externalFieldValue);
//				}
//				continue;
//			}
			// 来电号码
//			if (ConstantCode.WorkOrderBaseFieldMeanig.PHONE_FIELD.equals(innerFieldName)) {
//				if (StringUtils.isNotBlank(workOrder.getPhone())) {
//					pushInterfaceParams.put(externalFieldName, workOrder.getPhone());
//				} else {
//					pushInterfaceParams.put(externalFieldName, externalFieldValue);
//				}
//				continue;
//			}
			// 问题描述
//			if (ConstantCode.WorkOrderBaseFieldMeanig.PROBLEMDESC_FIELD.equals(innerFieldName)) {
//				if (StringUtils.isNotBlank(workOrder.getProblemDesc())){
//					pushInterfaceParams.put(externalFieldName, workOrder.getProblemDesc());
//				} else {
//					pushInterfaceParams.put(externalFieldName, externalFieldValue);
//				}
//				continue;
//			}
		}
		return pushInterfaceParams;
	}

	/**
	 * TODO 设置工单处理人（改派）
	 * @author: victor_tang
	 * @createtime: 2020/1/16 11:43
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void setWorkOrderHandlePerson(WorkOrder workOrder,
									  JSONObject triggerAction){
		String currentHandlePersonIds = null;
		String currentHandlePersonNames =null;
		List<String> userIdsList = null;

		String handleType = triggerAction.getString("containValue");
		if (ConstantCode.UserRoleDeptType.USER.equals(handleType)) {
			// 根据用户编码组装用户信息
			JSONArray containValueUser = triggerAction.getJSONArray("containValueUser");
			if (containValueUser==null||containValueUser.size()<1) {
				log.info("触发器设置工单处理人时，处理人id为空无法设置");
				return;
			}
			userIdsList = JSONArray.parseArray(containValueUser.toJSONString(), String.class);

			Map<String, Object> searchMap = new HashMap<>(2);
			searchMap.put("userIds",userIdsList);
			List<EwsUser> ewsUsers = ewsUserDao.selectAllUserList(searchMap);
			List userNamesList = new ArrayList<String>();
			for (EwsUser ewsUser : ewsUsers) {
				userNamesList.add(ewsUser.getName());
			}
			currentHandlePersonIds = StringUtils.join(userIdsList.toArray(), ",");
			currentHandlePersonNames = StringUtils.join(userNamesList.toArray(), ",");
		}
		else if (ConstantCode.UserRoleDeptType.ROLE.equals(handleType)) {
			// 根据角色编码组装用户信息
			JSONArray containValueUser = triggerAction.getJSONArray("containValueUser");
			if (containValueUser==null||containValueUser.size()<1) {
				log.info("触发器设置工单处理人时，处理角色id为空无法设置");
				return;
			}

			List roleIdsList = JSONArray.parseArray(containValueUser.toJSONString(),String.class);
			Map<String, Object> searchMap = new HashMap<>(2);
			searchMap.put("roleIds",roleIdsList);
			List<EwsUser> ewsUsers = ewsUserDao.selectUserListByRoleInfo(searchMap);

			List userNamesList = new ArrayList<String>();
			for (EwsUser ewsUser : ewsUsers) {
				userIdsList.add(ewsUser.getId());
				userNamesList.add(ewsUser.getName());
			}
			currentHandlePersonIds = StringUtils.join(userIdsList.toArray(), ",");
			currentHandlePersonNames = StringUtils.join(userNamesList.toArray(), ",");

		}
		else if (ConstantCode.UserRoleDeptType.DEPT.equals(handleType)) {
			// 根据部门编码组装用户信息
			JSONArray containValueUser = triggerAction.getJSONArray("containValueUser");
			if (containValueUser==null||containValueUser.size()<1) {
				log.info("触发器设置工单处理人时，处理人部门id为空无法设置");
				return;
			}
			List departmentIdsList = commonUtil.splitDeptCode(containValueUser.toJSONString());
			Map<String, Object> searchMap = new HashMap<>(2);
			searchMap.put("departmentIds",departmentIdsList);
			List<EwsUser> ewsUsers = ewsUserDao.selectAllUserList(searchMap);

			List userNamesList = new ArrayList<String>();
			for (EwsUser ewsUser : ewsUsers) {
				userIdsList.add(ewsUser.getId());
				userNamesList.add(ewsUser.getName());
			}
			currentHandlePersonIds = StringUtils.join(userIdsList.toArray(), ",");
			currentHandlePersonNames = StringUtils.join(userNamesList.toArray(), ",");

		}

		// 修改流程引擎中当前工单任务处理人信息
		updateWorkHandlePersonInfoOfProcessTask(workOrder.getProcessInstanceId(),userIdsList);

		// 设置工单更新信息
		workOrder = setWorkOrderUpdateInfo(workOrder,currentHandlePersonIds,
				currentHandlePersonNames);
		workOrderDao.updateByPrimaryKeySelective(workOrder);

		// 记录日志
		WorkOrderLog workOrderLog = getWorkOrderLogInfo(workOrder);
		workOrderLogService.addSave(workOrderLog);

	}
	/**
	 * TODO 组装工单改派log信息
	 * @author: victor_tang
	 * @createtime: 2020/1/16 14:08
	 * @param workOrderParam 1
	 * @return: com.egoo.ews.service.vo.WorkOrderLog
	 */
	private WorkOrderLog getWorkOrderLogInfo(WorkOrder workOrderParam) {
		WorkOrderLog workOrderLog = new WorkOrderLog();
		WorkOrder workOrder = workOrderDao.selectById(workOrderParam.getId());
		workOrderLog.setWorkOrderId(workOrder.getId());
		workOrderLog.setWorkOrderNodeId(workOrder.getCurrentWorkOrderNodeId());
		workOrderLog.setWorkOrderStatusId(workOrder.getStatusId());
		workOrderLog.setLogCreateTime(new Date());
		workOrderLog.setLogCreaterId(ConstantCode.TriggerActionlogo.CODE);
		workOrderLog.setLogType(ConstantCode.WorkOrderLogType.REASSIGN_CODE);
		String contentString = "改派此工单给" + workOrderParam.getCurrentHandlerName() + "去处理";
		workOrderLog.setContent(contentString);
		workOrderLog.setWorkOrderNodeName(workOrder.getCurrentWorkOrderNodeName());
		return workOrderLog;
	}
	/**
	 * TODO 修改流程引擎中当前工单任务处理人信息
	 * @author: victor_tang
	 * @createtime: 2020/1/16 14:05
	 * @param processInstanceId 1
	 * @param userIdsList 2
	 * @return: void
	 */
	private void updateWorkHandlePersonInfoOfProcessTask(String processInstanceId,List<String> userIdsList){
		String taskId = ActTaskServiceUtil.getActiveTaskIdByProcessInstId(processInstanceId);
		for (String currentHandlerId : userIdsList) {
			ActTaskServiceUtil.updateCurrentHandler(taskId, currentHandlerId);
		}
	}
	/**
	 * TODO 设置工单更新信息
	 * @author: victor_tang
	 * @createtime: 2020/1/16 13:43
	 * @param workOrder 1
	 * @param currentHandlePersonIds 2
	 * @param currentHandlePersonNames 3
	 * @return: com.egoo.ews.service.vo.WorkOrder
	 */
	private WorkOrder setWorkOrderUpdateInfo(WorkOrder workOrder,
											 String currentHandlePersonIds,String currentHandlePersonNames){
		// 设置工单信息信息
		workOrder.setCurrentHandlerId(currentHandlePersonIds);
		workOrder.setCurrentHandlerName(currentHandlePersonNames);
		workOrder.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
		workOrder.setLastUserId(ConstantCode.TriggerActionlogo.CODE);
		workOrder.setLastUserName(ConstantCode.TriggerActionlogo.NAME);
		return workOrder;
	}
	/**
	 * TODO 设置工单状态
	 * @author: victor_tang
	 * @createtime: 2020/1/15 15:35
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void setWorkOrderStatus(WorkOrder workOrder, JSONObject triggerAction){
		Integer workOrderStatusId = triggerAction.getInteger("containValue");
		if (ConstantCode.WorkOrderState.ALREDAY_CLOSE==workOrderStatusId
				||ConstantCode.WorkOrderState.ALREAAY_CASE==workOrderStatusId
		) {
			workOrder.setCloseTime(new Timestamp(System.currentTimeMillis()));
			workOrder.setCloseUserId(ConstantCode.TriggerActionlogo.CODE);
			workOrder.setCloseUserName(ConstantCode.TriggerActionlogo.NAME);
		}
		WorkOrderStatus workOrderStatusVo = workOrderStatusDao.selectById(workOrderStatusId,workOrder.getTenantId());
		workOrder.setStatusId(workOrderStatusId);
		workOrder.setStatusName(workOrderStatusVo.getName());
		workOrder.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
		workOrder.setLastUserId(ConstantCode.TriggerActionlogo.CODE);
		workOrder.setLastUserName(ConstantCode.TriggerActionlogo.NAME);

		Integer result = workOrderDao.updateWorkOrder(workOrder);
		if (result!=1) {
			log.error(workOrder.getId()+"工单，触发器设置工单状态失败！");
		}
		// 设置触发器时间类条件过期时间
		if (ConstantCode.WorkOrderState.ALREDAY_CLOSE==workOrderStatusId
				||ConstantCode.WorkOrderState.ALREAAY_CASE==workOrderStatusId
			) {
			setWorkOrderTimeConditionTrigger(workOrder.getId()+"");
		}
	}
	/**
	 * TODO 设置工单优先级
	 * @author: victor_tang
	 * @createtime: 2020/1/15 19:03
	 * @param workOrder 1
	 * @param triggerAction 2
	 * @return: void
	 */
	private void setWorkOrderPriority(WorkOrder workOrder, JSONObject triggerAction){
		String priority = triggerAction.getString("containValue");
		workOrder.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
		workOrder.setLastUserId(ConstantCode.TriggerActionlogo.CODE);
		workOrder.setLastUserName(ConstantCode.TriggerActionlogo.NAME);

		Integer result = workOrderDao.updateWorkOrder(workOrder);
		if (result!=1) {
			log.error(workOrder.getId()+"工单，触发器设置工单优先级失败！");
		}
	}
	/**
	 * TODO 动态拼接触发器查询sql
	 * @author: victor_tang
	 * @createtime: 2020/1/15 13:59
	 * @param triggerCondition 1
	 * @return: java.lang.String
	 */
	private String dynamicJoinSql(JSONObject triggerCondition, String workOrderId){

		String sql =
				"select a.*,b.work_order_monitor_id,b.sender from work_order a,work_order_relation b where" +
						" a.id = b.work_order_id and a.id = '"+ workOrderId+"'";
		String allConditionSql = "";
		String randomConditionSql = "";

		JSONArray allConditionsTableData = triggerCondition.getJSONArray("allConditionsTableData");
		if (allConditionsTableData!=null && allConditionsTableData.size()>0) {
			JSONObject allConditionsObject = new JSONObject();
			allConditionsObject.put("condition",allConditionsTableData);
			// 拼接满足所有条件
			allConditionSql = dynamicSqlJoinUtil.joinSqlCondition(allConditionsObject, "", null,
					ConstantCode.SqlRelationKey.AND);
		}
		if (StringUtils.isNotBlank(allConditionSql)) {
			int index = allConditionSql.indexOf(ConstantCode.SqlRelationKey.AND);
			allConditionSql	= allConditionSql.substring(index+3);
		}

		JSONArray randomConditionsTableData = triggerCondition.getJSONArray("randomConditionsTableData");
		if (randomConditionsTableData!=null && randomConditionsTableData.size()>0) {
			JSONObject randomConditionsObject = new JSONObject();
			randomConditionsObject.put("condition",randomConditionsTableData);
			// 拼接满足任意条件
			randomConditionSql = dynamicSqlJoinUtil.joinSqlCondition(randomConditionsObject, "", null,
					ConstantCode.SqlRelationKey.OR);
		}
		if (StringUtils.isNotBlank(randomConditionSql)) {
			int index = randomConditionSql.indexOf(ConstantCode.SqlRelationKey.OR);
			randomConditionSql	= randomConditionSql.substring(index+2);
		}
		return handleFinalSql(sql,allConditionSql,randomConditionSql);
	}
	/**
	 * TODO 组装最终查询sql
	 * @author: victor_tang
	 * @createtime: 2020/4/14 19:01
	 * @param sql 1
	 * @return: java.lang.String
	 */
	private String handleFinalSql(String sql,String allConditionSql, String randomConditionSql){
		StringBuffer sb = new StringBuffer();
		if (StringUtils.isEmpty(allConditionSql)&& StringUtils.isEmpty(randomConditionSql)) {
			return sql;
		}
		else if (StringUtils.isNotBlank(allConditionSql)&& StringUtils.isNotBlank(randomConditionSql)) {
			sb.append(sql).append(" and (")
								.append("(")
									.append(allConditionSql)
								.append(")")
								.append(" and ")
								.append("(")
									.append(randomConditionSql)
								.append(")")
							.append(")");
			return sb.toString();
		}
		else if (StringUtils.isEmpty(allConditionSql)) {
			sb.append(sql).append(" and (")
							  .append(randomConditionSql)
					      .append(")");
			return sb.toString();
		} else {
			sb.append(sql).append(" and (")
							  .append(allConditionSql)
					      .append(")");
			return sb.toString();
		}
	}
	/**
	 * TODO 设置触发器时间类到期触发时间
	 * @author: victor_tang
	 * @createtime: 2020/1/14 13:50
	 * @param workOrderId 1
	 * @return: void
	 */
	@Override
	public void setWorkOrderTimeConditionTrigger(String workOrderId) {
		List<WorkOrderTriggerInfoVo> nomalTriggerList = getNomalTriggerInfoList(workOrderId);
		log.info("租户可见启用状态的所有触发器列表数据(时间类到期)==》"+nomalTriggerList);
		if (CollectionUtils.isEmpty(nomalTriggerList)) {
			return;
		}
		// 遍历启用状态的触发器列表
		for (WorkOrderTriggerInfoVo workOrderTriggerInfoVo : nomalTriggerList) {
			// 校验此触发器工单是否可执行
			Boolean flag = checkIsExecuted(workOrderTriggerInfoVo, workOrderId);
			if (flag) {
				setKeyOverdueTime(workOrderTriggerInfoVo, workOrderId);
			}
		}
	}
	/**
	 * TODO 设置触发器时间类条件key过期时间
	 * @author: victor_tang
	 * @createtime: 2020/1/14 14:01
	 * @param workOrderTriggerInfoVo 1
	 * @param workOrderId 2
	 * @return: void
	 */
	private void setKeyOverdueTime(WorkOrderTriggerInfoVo workOrderTriggerInfoVo,String workOrderId){
		JSONObject triggerCondition = workOrderTriggerInfoVo.getTriggerCondition();
		if (triggerCondition==null) {
			log.info(workOrderTriggerInfoVo.getId()+"触发器条件为空！");
			return;
		}
		JSONArray triggerConditionArray = new JSONArray();
		JSONArray allConditionsTableData = triggerCondition.getJSONArray("allConditionsTableData");
		JSONArray randomConditionsTableData = triggerCondition.getJSONArray("randomConditionsTableData");
		if (allConditionsTableData!=null) {
			triggerConditionArray.addAll(allConditionsTableData);
		}
		if (randomConditionsTableData!=null) {
			triggerConditionArray.addAll(randomConditionsTableData);
		}
		for (int i = 0; i < triggerConditionArray.size(); i++) {
			// 过滤器一级id
			Integer filterFirstId =
					triggerConditionArray.getJSONObject(i).getJSONObject(
							"firstId").getInteger("value");
			// 过滤器二级id
			Integer filterSecondId = triggerConditionArray.getJSONObject(i).getJSONObject(
					"secondDataId").getInteger("value");

			if (ConstantCode.FilterFirst.WORK_ORDER_CREATED_TIME_ID!=filterFirstId
					&& ConstantCode.FilterFirst.WORK_ORDER_CLOSED_TIME_ID!=filterFirstId
			) {
				// 非时间类触发条件，直接跳出
				return;
			}

			if(ConstantCode.FilterSecond.BETWEEN_ID_SIX==filterSecondId){
				// 大于  介于  小于（单位：小时）
				setKeyOverdueTimeOfTimeType(triggerConditionArray.getJSONObject(i),workOrderId);
			}

		}
	}
	/**
	 * TODO 设置时间类key过期时间
	 * @author: victor_tang
	 * @createtime: 2020/1/14 18:26
	 * @param triggerCondition 1
	 * @param workOrderId 2
	 * @return: void
	 */
	private void setKeyOverdueTimeOfTimeType(JSONObject triggerCondition,
                                             String workOrderId){
		WorkOrder workOrder = workOrderDao.selectById(workOrderId);
		Long createTimes = workOrder.getCreateTime().getTime();
		Long closeTimes = null;
		if (workOrder.getCloseTime()!=null) {
			closeTimes	= workOrder.getCloseTime().getTime();
		}

		// 二级过滤器选择值
		Integer filterSecondVal = triggerCondition.getJSONObject(
				"secondDataId").getInteger("value");

		if (ConstantCode.FilterSecondVal.LARGE_ONE==filterSecondVal) {
			// 选择或者输入的最终值（大于）
			String finalVale = triggerCondition.getString("value");
			Long lagerTimes= (Long.valueOf(finalVale))*60*60*1000L;
			Long createOverdueTimes = computeOverdueTimes(createTimes, lagerTimes);
			if (createOverdueTimes!=null) {
				redisUtil.set(RedisKeyConstant.WORK_ORDER_CREATE_TIME_PREFIX+workOrderId,
						RedisKeyConstant.WORK_ORDER_CREATE_TIME_PREFIX+workOrderId,createOverdueTimes);
			}

			Long closeOverdueTimes = computeOverdueTimes(closeTimes,lagerTimes);
			if (closeOverdueTimes!=null) {
				redisUtil.set(RedisKeyConstant.WORK_ORDER_CLOSE_TIME_PREFIX+workOrderId,
						RedisKeyConstant.WORK_ORDER_CLOSE_TIME_PREFIX+workOrderId,closeOverdueTimes);
			}

		}else if (ConstantCode.FilterSecondVal.BETWEEN_THREE==filterSecondVal) {
			// 选择或者输入的最终值（介于）
			JSONArray finalValArray = triggerCondition.getJSONArray("value");
			String startTime = finalValArray.getString(0);
			Long lagerTimes= (Long.valueOf(startTime))*60*60*1000L;
			Long createOverdueTimes = computeOverdueTimes(createTimes, lagerTimes);
			if (createOverdueTimes!=null) {
				redisUtil.set(RedisKeyConstant.WORK_ORDER_CREATE_TIME_PREFIX+workOrderId,
						RedisKeyConstant.WORK_ORDER_CREATE_TIME_PREFIX+workOrderId,createOverdueTimes);
			}

			Long closeOverdueTimes = computeOverdueTimes(closeTimes,lagerTimes);
			if (closeOverdueTimes!=null) {
				redisUtil.set(RedisKeyConstant.WORK_ORDER_CLOSE_TIME_PREFIX+workOrderId,
						RedisKeyConstant.WORK_ORDER_CLOSE_TIME_PREFIX+workOrderId,closeOverdueTimes);
			}
		}
	}
	/**
	 * TODO 计算触发点时间
	 * @author: victor_tang
	 * @createtime: 2020/1/15 10:26
	 * @param businuesTimes 1
	 * @param criticalPointTimes 2
	 * @return: java.lang.Long
	 */
	private Long computeOverdueTimes(Long businuesTimes,Long criticalPointTimes){
		if (businuesTimes==null) {
			// 业务时间为空，不在设置触发点
			return null;		
		}
		Long targetTimes = businuesTimes+criticalPointTimes;
		Long nowTimes = System.currentTimeMillis();
		Long overdueTimes = targetTimes - nowTimes;
		if (overdueTimes<0) {
			// 当前时间超过临界点时间，代表已触发，不在设置触发点
			return null;
		}
		return overdueTimes;
	}

	/**
	 * TODO 处理预约回电业务
	 * @author: victor_tang
	 * @createtime: 2020/4/1 11:15
	 * @param workOrderId 1
	 * @return: void
	 */
	@Override
	public void handlePrepareToWarnPhoneBusi(String workOrderId) {
		WorkOrder workOrder = workOrderDao.selectById(workOrderId);
		if (workOrder==null) {
			log.info("预约回电业务处理时，根据工单id获取工单信息为空！");
		}
		String currentHandlerIds= workOrder.getCurrentHandlerId();
		if (StringUtils.isEmpty(currentHandlerIds)) {
			log.info("预约回电业务处理时,当前处理人信息为空！");
		}
		// 获取预约回电短信模板
		String content=
		getMsgTemplateContent(ConstantCode.TemplateConfig.CALL_PHONE_TEMPLATE_NAME);
		if (StringUtils.isEmpty(content)){
			log.info("获取预约回电模板为空，无法推送消息！");
			return;
		}
		content = content.replace("{workOrderId}", workOrderId);
		// 给当前处理人推送预约回电提醒消息
		SystemMsgDto systemMsgDto = new SystemMsgDto();
		systemMsgDto.setSenderId(ConstantCode.SystemMsgConfig.SENDER_ID_SYS);
		systemMsgDto.setTitle(ConstantCode.TemplateConfig.CALL_PHONE_TEMPLATE_NAME);
		systemMsgDto.setContent(content);
		systemMsgDto.setTargets(Arrays.asList(currentHandlerIds.split(",")));
		JSONObject jsonObject = getPushMsgParamRemark(workOrder.getId(),
				ConstantCode.SystemMsgConfig.IS_JUMP_Y,
				ConstantCode.SystemMsgConfig.WORK_ORDER);
		systemMsgDto.setRemark(jsonObject);
		eripDataSynService.sendSystemMsg(systemMsgDto);
	}
	/**
	 * TODO 获取内管内置短信模板
	 * @author: victor_tang
	 * @createtime: 2020/4/1 11:25
	 * @param filterName 1
	 * @return: java.lang.String
	 */
	private String getMsgTemplateContent(String filterName){
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isNotBlank(filterName)) {
			jsonObject.put("name",filterName);
		}
		JSONArray templateArr = eripDataSynService.getTemplateByFilterCondition(jsonObject);
		if (templateArr==null||templateArr.size()==0) {
			log.info("触发器执行，过滤条件{name}为"+filterName+"获取内管配置短信模板为空！");
			return null;
		}
		return templateArr.getJSONObject(0).getString("remark");
	}
	
}
